var BaseFun = require('./Function'),
    BaseEnum = require('./Enum'),
    entityCollection = require('./EntityCollection'),
    Transaction = require('./Transaction');

//单个保存文档，根据有无_id值判断是否新增还是修改
//返回值：当前被保存的文档
exports.save = function(req, responseFun) {
    //BaseFun.authorizedCheck(req.user, res);

    var parameter = req.body;
    var entityName = parameter.EntityName;
    var records = parameter.Records;

    for (var i = 0; i < records.length; i++) {
        if (records[i].RowStatus == BaseEnum.RowStatus.Insert.Value) {
            records[i].CreatedBy = req.user.Code;
        }
        else if (records[i].RowStatus == BaseEnum.RowStatus.Modify.Value) {
            records[i].ModifyBy = req.user.Code;
        }
    }
    
    Transaction.BatchSaveByTran([{EntityName: entityName, Records: records}], responseFun);
};

//批量保存文档，根据有无_id值判断是否新增还是修改
//返回值：当前被保存的文档集合
exports.saves = function(req, responseFun) {
    // BaseFun.authorizedCheck(req.user, res);

    var parameter = req.body;
    var entityRecords = parameter.EntityRecords;

    for (var i = 0; i < parameter.EntityRecords.length; i++) {
        for (var j = 0; j < parameter.EntityRecords[i].Records.length; j++) {
            if (parameter.EntityRecords[i].Records[j].RowStatus == BaseEnum.RowStatus.Insert.Value) {
                parameter.EntityRecords[i].Records[j].CreatedBy = req.user.Code;
            } else if (parameter.EntityRecords[i].Records[j].RowStatus == BaseEnum.RowStatus.Modify.Value) {
                parameter.EntityRecords[i].Records[j].ModifyBy = req.user.Code;
            }
        }
    }

    Transaction.BatchSaveByTran(entityRecords, responseFun);
};

exports.updateByValue = function(req, responseFun) {
    // BaseFun.authorizedCheck(req.user, res);

    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);

    entity.updateByValue(parameter.Condition, parameter.Value, responseFun);
};

//按条件删除文档
//返回值：删除的条数
exports.delete = function(req, responseFun) {
    // BaseFun.authorizedCheck(req.user, res);

    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);

    entity.deleteById(parameter.Record._id, responseFun);
};
//按多个条件遍历批量删除文档
//返回值：删除的条数
exports.deletes = function(req, responseFun) {
    // BaseFun.authorizedCheck(req.user, res);

    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);
    var conditions = parameter.Conditions;
    var result = 0;
    var isErr = false;

    var callbackFun = function(err, result) {
        if (err) {
            isErr = true;
        }
        result++;
        if (result == conditions.length) {
            if (isErr) {
                var newErr = new Error();
                newErr.level = 5;
                newErr.title = '删除失败';
                newErr.message = '删除失败，请重试';

                responseFun(newErr);
            } else {
                responseFun(null, true);
            }
        }
    };

    for (var condition in conditions) {
        entity.deleteByCondition(condition, callbackFun);
    }
};
//按_id单个删除文档
//返回值：删除的条数
exports.deleteById = function(req, responseFun) {
    // BaseFun.authorizedCheck(req.user, res);

    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);
    entity.deleteById(parameter.ID, responseFun);
};
//按_id集合批量删除文档
//返回值：删除的条数
exports.deleteByIds = function(req, responseFun) {
    // BaseFun.authorizedCheck(req.user, res);

    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);
    entity.deleteByIds(parameter.IDs, responseFun);
};
exports.deleteByCondition = function(req, responseFun) {
    // BaseFun.authorizedCheck(req.user, res);

    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);

    entity.deleteByCondition(parameter.Condition, responseFun);
};

//按条件查找文档
//返回值：所有符合条件的文档
exports.find = function(req, responseFun) {
    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);

    //entity.Entity.schema.paths.CreatedOn.options.type == Date 获取字段类型样例
    var condition = parameter.Condition;
    entity.find(condition, parameter.OrderBy, parameter.Populate, responseFun);
};
//按_id查找文档
//返回值：当前_id所对应的文档
exports.findById = function(req, responseFun) {
    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);

    entity.findById(parameter.ID, parameter.Populate, responseFun);
};
//按条件查找文档是否存在
//返回值：满足条件的第一个文档
exports.findOne = function(req, responseFun) {
    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);
    entity.findOne(parameter.Condition, parameter.Populate, responseFun);
};

exports.search = function(req, responseFun) {
    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);
    if (parameter.Condition == undefined) {
        parameter.Condition = null;
    }
    if (parameter.Limit == undefined) {
        parameter.Limit = null;
    }

    entity.search(parameter.Text, parameter.Condition, parameter.Limit, responseFun);
    //entity.collection.command("text", {search: "phrase"});
    //this.db.command({text:"collection" , search: "phrase" }).
    //‌‌this.Entity.db.db.executeDbCommand
    //‌‌this.Entity.db.db.executeDbCommand({text:"Department" , search: "vt" },function(err, res){Console.log(err.toString() + res.toString())})
};

//根据条件查找满足条件的该文档所在条件集合的索引位置，为翻页功能提供
//返回值：当前满足条件的文档所对应的索引位置
exports.findRecordIndex = function(req, responseFun) {
    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);

    entity.findRecordIndex(parameter.ID, parameter.Condition, parameter.OrderBy, responseFun);
};
//查找某一页的全部文档
//返回值：该页的全部文档
exports.pageQuery = function(req, responseFun) {
    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);
    entity.pageQuery(parameter.Condition, parameter.OrderBy,
        parameter.Populate, parameter.PageNum, parameter.PageSize,
        responseFun
    );
};
//查找满足条件的文档个数
//返回值：满足条件的文档个数
exports.queryRecordCount = function(req, responseFun) {
    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);
    entity.queryRecordCount(parameter.Condition, responseFun);
};

//获取实体字段
exports.getEntityMetadata = function(req, responseFun) {
    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);
    var entityMetadata = {
        EntityName: entity.EntityName,
        Name: entity.Name,
        Fields: entity.Fields
    };
    
    responseFun(null, entityMetadata);
};

exports.distinct = function(req, responseFun){
    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);
    entity.distinct(parameter.Field, parameter.Condition, responseFun);
};

//聚合查询
exports.aggregate = function(req, responseFun){
    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);
    entity.aggregate(parameter.Arguments, responseFun);
};

exports.mapReduce = function(req, responseFun){
    var parameter = req.body;
    var entity = entityCollection.getEntity(parameter.EntityName);
    entity.mapReduce(parameter.Option, parameter.Condition, parameter.OrderBy, responseFun);
};

